﻿using UnityEngine;
using UnityEngine.Rendering;
using Yoozoo.Core.Extensions.CSharp;

namespace Yoozoo.Gameplay.Liberty.AI
{
    public class LibertyNpcLodController : MonoBehaviour
    {

        /// <summary>
        /// 所有的MeshRenderer
        /// </summary>
        [Header("所有的MeshRenderer")]
        public SkinnedMeshRenderer[] Renderers;

        /// <summary>
        /// LOD2下需要隐藏的MeshRenderer
        /// </summary>
        [Header("LOD2下需要隐藏的MeshRenderer")]
        public SkinnedMeshRenderer[] Lod2;

        private int _lod = -1;

        public void ChangeLod(int lod)
        {
            if (_lod == lod)
                return;

            //UnityEngine.Debug.Log($"{transform.parent.parent.name} change lod from {_lod} to {lod}", gameObject);
            _lod = lod;
            if (lod == 0)
            {
                foreach (var skinnedMeshRenderer in Renderers)
                {
                    skinnedMeshRenderer.shadowCastingMode = ShadowCastingMode.On;
                }

                foreach (var skinnedMeshRenderer in Lod2)
                {
                    skinnedMeshRenderer.enabled = true;
                }
            }
            else if (lod == 1)
            {
                foreach (var skinnedMeshRenderer in Renderers)
                {
                    skinnedMeshRenderer.shadowCastingMode = ShadowCastingMode.Off;
                }

                foreach (var skinnedMeshRenderer in Lod2)
                {
                    skinnedMeshRenderer.enabled = true;
                }
            }
            else
            {
                foreach (var skinnedMeshRenderer in Renderers)
                {
                    skinnedMeshRenderer.shadowCastingMode = ShadowCastingMode.Off;
                }

                foreach (var skinnedMeshRenderer in Lod2)
                {
                    skinnedMeshRenderer.enabled = false;
                }
            }
        }

#if UNITY_EDITOR
        void OnValidate()
        {
            if (Renderers.IsEmpty() && Lod2.IsEmpty())
            {
                Renderers = gameObject.GetComponentsInChildren<SkinnedMeshRenderer>(true);
                Lod2 = Renderers;
            }
        }
#endif
    }
}
